<script>
import { defineComponent, ref, computed, watch } from 'vue';
import { createNamespace, transformStyleSize } from '../utils';

import FanLoading from '../loading/loading.vue';
import FanIcon from '../icon/icon.vue';
import FanButton from '../button/button.vue';

export default defineComponent({
  name: createNamespace('LoadingView')[0],
  options: {
    // https://uniapp.dcloud.io/matter.html#mp
    virtualHost: true,
  },
  components: { FanLoading, FanIcon, FanButton },
  emits: ['buttonClick'],
  props: {
    customStyle: [String, Object],
    loading: Boolean,
    // string: message | object: { message, button }
    error: [String, Object],
    color: String,
    type: {
      type: String,
      default: 'circle2',
    },
    // 用绝对定位撑满父盒子
    full: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, context) {
    const theStyle = computed(() => transformStyleSize(props.customStyle));
    const showLoading = ref(false);
    const errorInfo = computed(() => {
      const { error } = props;
      if (!error) return null;
      if (typeof error === 'string') return { message: error };
      return error;
    });
    watch(
      () => props.loading,
      (val) => {
        if (!val) {
          showLoading.value = false;
          return;
        }
        setTimeout(() => {
          if (props.loading) showLoading.value = true;
        }, 300);
      },
      { immediate: true },
    );

    const onClick = (e) => {
      context.emit('buttonClick', e);
    };

    return { theStyle, showLoading, errorInfo, onClick };
  },
});
</script>

<template>

  <div v-if="loading" :class="['fan-loading-view', { 'fan-loading-view--full': full }]" :style="theStyle">
    <div v-if="!errorInfo">
      <FanLoading v-if="showLoading" :color="color" :type="type" />
    </div>
    <template v-else>
      <slot name="errorIcon">
        <FanIcon name="warning-circle-fill" :size="34" color="var(--fan-danger-color)" />
      </slot>
      <div v-if="errorInfo.message" class="fan-loading-view__t">
        {{ errorInfo.message }}
      </div>
      <FanButton v-if="errorInfo.button" round bold radius="20px" style="min-width: 100px;" @click="onClick">{{
    errorInfo.button }}</FanButton>
    </template>
  </div>

  <div v-else :style="theStyle">
    <slot />
  </div>
</template>

<style lang="less">
.fan-loading-view {
  width: 100%;
  height: 100%;
  min-height: 50px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  color: #666;
  word-break: break-all;

  &--full {
    position: absolute;
    top: 0;
    left: 0;
  }
}

.fan-loading-view__t {
  text-align: center;
  margin: 7px 10px 15px;
  max-height: 170px;
  // uniapp 高度 0 ？？
  // overflow: hidden;
}
</style>
